package com.gydz.gydzbaseframeworkboot.SystemControl.controller;

import com.gydz.gydzbaseframeworkboot.SystemControl.dao.OperationLogMapper;
import com.gydz.gydzbaseframeworkboot.SystemControl.domain.DepartmentInformation;
import com.gydz.gydzbaseframeworkboot.SystemControl.domain.OperationLog;
import com.gydz.gydzbaseframeworkboot.SystemControl.domain.User;
import com.gydz.gydzbaseframeworkboot.SystemControl.service.DepartmentInformationService;
import com.gydz.gydzbaseframeworkboot.SystemControl.service.UserService;
import com.gydz.gydzbaseframeworkboot.SystemControl.utils.Log;
import com.gydz.gydzbaseframeworkboot.Common.utils.export.ExcelUtil;
import com.gydz.gydzbaseframeworkboot.Common.utils.export.ImportExcelUtil;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.PageParam;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.PageUtils;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.TableDataInfo;
import com.gydz.gydzbaseframeworkboot.Common.utils.queryParam.QueryParam;
import com.gydz.gydzbaseframeworkboot.Common.utils.result.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/system")
public class SystemControlController {
    @Resource
    OperationLogMapper operationLogMapper;

    @Resource
    UserService userService;

    @Resource
    DepartmentInformationService departmentInformationService;

    /**
     * 用户管理页面
     */
    @GetMapping("/userList")
    public ModelAndView lserListModelAndView(ModelAndView modelAndView) {
        modelAndView.setViewName("systemControl/userList");
        return modelAndView;
    }

    /**
     * 用户管理查询
     */
    @ResponseBody
    @Log(remark = "查询用户列表")
    @PostMapping("/userList")
//    @PreAuthorize("hasAuthority('admin') or hasAuthority('test')" )
    public void userList(HttpServletResponse httpServletResponse, @ModelAttribute("queryParam") QueryParam queryParam) throws IOException {
        PageUtils.startPage(new PageParam(queryParam.getiDisplayStart(),queryParam.getiDisplayLength(),queryParam.getsSortDir(),queryParam.getsSortCol()));

        List<User> userList = userService.selectUserList(queryParam);
        TableDataInfo tableDataInfo = PageUtils.getDataTable(userList);

        ResultUtils result =  ResultUtils.succ(200,"获取用户息成功",tableDataInfo);
        ResultUtils.responseResult(httpServletResponse,result);
    }

    /**
     * 查询用户信息
     * @param httpServletResponse
     * @throws IOException
     */
    @Log(remark = "查询用户列表")
    @PostMapping("/userInfoByName")
//    @PreAuthorize("hasAuthority('admin') or hasAuthority('test')" )
    public void userInfoByName(HttpServletResponse httpServletResponse, @ModelAttribute("account") String account) throws IOException {
        User user = userService.getByUserNameInfo(account);
        ResultUtils result =  ResultUtils.succ(user);
        ResultUtils.responseResult(httpServletResponse,result);
    }

    /**
     * 新增用户
     */
    @PostMapping("/user/save")
    @Log(remark = "新增用户", openType = "0")
    @PreAuthorize("hasAuthority('admin') or hasAuthority('管理员')" )
    public void userSave(HttpServletResponse httpServletResponse, @ModelAttribute("user") User user) throws IOException {
        userService.insertUser(user);
        ResultUtils result =  ResultUtils.succ("新增用户成功");
        ResultUtils.responseResult(httpServletResponse,result);
    }

    /**
     * 判断用户是否存在
     */
    @PostMapping("/user/isExist")
    @PreAuthorize("hasAuthority('admin') or hasAuthority('管理员')" )
    public void userIsExist(HttpServletResponse httpServletResponse, String account) throws Exception {
        ResultUtils result =  ResultUtils.succ(userService.getByUserName(account));
        ResultUtils.responseResult(httpServletResponse,result);
    }

    /**
     * 部门信息
     */
    @PostMapping("/user/getItems")
//    @PreAuthorize("hasAuthority('admin') or hasAuthority('test')" )
    public void getItems(HttpServletResponse httpServletResponse, DepartmentInformation departmentInformation) throws Exception {
        ResultUtils result =  ResultUtils.succ(departmentInformationService.optionList(departmentInformation));
        ResultUtils.responseResult(httpServletResponse,result);
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/user/updateUser")
    @Log(remark = "修改用户信息", openType = "2")
//    @PreAuthorize("hasAuthority('admin') or hasAuthority('test')" )
    public void updateUser(HttpServletResponse httpServletResponse, @ModelAttribute("user") User user) throws IOException {
        ResultUtils result =  ResultUtils.succ(200,"修改用户成功",userService.updateUser(user));
        ResultUtils.responseResult(httpServletResponse,result);
    }

    /**
     * 修改用户密码
     */
    @PostMapping("/user/updateUserPwd")
    @Log(remark = "修改用户密码", openType = "2")
//    @PreAuthorize("hasAuthority('admin') or hasAuthority('test')" )
    public void updateUserPwd(HttpServletResponse httpServletResponse, Long id, String password) throws Exception {
        ResultUtils result =  ResultUtils.succ(userService.updateUserPwd(id, password));
        ResultUtils.responseResult(httpServletResponse,result);
    }

    /**
     * 重置用户密码
     */
    @PostMapping("/user/resetUserPwd")
    @Log(remark = "重置用户密码", openType = "2")
//    @PreAuthorize("hasAuthority('admin') or hasAuthority('test')" )
    public void resetUserPwd(HttpServletResponse httpServletResponse, Long id) throws Exception {
        ResultUtils result =  ResultUtils.succ(userService.resetUserPwd(id));
        ResultUtils.responseResult(httpServletResponse,result);
    }



    /**
     * 删除用户
     */
    @GetMapping("/user/del")
    @Log(remark = "删除用户", openType = "1")
    @PreAuthorize("hasAuthority('admin') or hasAuthority('管理员')" )
    public void del(HttpServletResponse httpServletResponse, Long id) throws Exception {
        userService.deleteUserById(id);

        ResultUtils result =  ResultUtils.succ("删除用户成功");
        ResultUtils.responseResult(httpServletResponse,result);
    }

    /**
     * 导出用户信息
     */
    @RequestMapping("/userList/exprotData")
    @PreAuthorize("hasAuthority('admin') or hasAuthority('管理员') or hasAuthority('test')" )
    public void exprotUser(HttpServletRequest request, @ModelAttribute("queryParam") QueryParam queryParam, HttpServletResponse response) {
        String[] excelHeader = {"序号", "用户名称", "登录账号", "创建日期", "用户角色", "所属部门", "所属站段", "所属车间", "所属工区"};
        String[] ds_titles = {"index", "userName", "account", "createTime", "accountAttributes", "deptName", "sectionName", "workshop", "workArea"};
        int[] widths = {256 * 14, 256 * 24, 256 * 24, 256 * 24, 256 * 19, 256 * 19, 256 * 19, 256 * 19, 256 * 19};
        int[] ds_format = {2, 2, 2, 2, 2, 2, 2, 2, 2};
        try {
            List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
            System.out.println("keyword:" + queryParam.getKeyword());

            List<User> list = userService.selectUserList(queryParam);

            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
            if (list != null && !list.isEmpty()) {
                int index = 1;
                for (User rdata : list) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("index", index);
                    index++;
                    map.put("userName", rdata.getUserName());
                    map.put("account", rdata.getAccount());
                    map.put("createTime", rdata.getCreateTime() != null ? format.format(rdata.getCreateTime()) : "");
                    map.put("accountAttributes", StringUtils.equals(rdata.getAccount(), "admin") ? "超级系统管理员" : rdata.getAccountAttributes());
                    map.put("deptName", rdata.getDeptName());
                    map.put("sectionName", rdata.getSectionName());
                    map.put("workshop", rdata.getWorkshop());
                    map.put("workArea", rdata.getWorkArea());
                    data.add(map);
                }
            }
            ExcelUtil.export("用户列表数据", "数据列表", excelHeader, ds_titles, ds_format, widths, data, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 导入用户信息模板
     */
    @GetMapping("/user/exportTemplate")
    public void exportTemplate(HttpServletRequest request, HttpServletResponse response){
        try{
            String[] excelHeader = {"序号", "用户名称", "登录账号", "所属部门", "所属站段", "所属车间", "所属工区"};
            String[] ds_titles = {"index", "userName", "account", "deptName", "sectionName", "workshop", "workArea"};
            int[] widths = {256 * 14, 256 * 24, 256 * 24, 256 * 24, 256 * 19, 256 * 19, 256 * 19};
            int[] ds_format = {2, 2, 2, 2, 2, 2, 2};
            ExcelUtil.exportTemplate("用户批量导入模板", "数据列表", excelHeader, ds_titles, ds_format, widths, request, response);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 导入用户信息
     */
    @PostMapping("/user/uploadFile")
    @Log(remark = "导入用户信息", openType = "0")
    public void  uploadFile(@RequestParam("file") MultipartFile file, HttpServletResponse httpServletResponse) throws Exception {
        InputStream in = file.getInputStream();
        List<List<Object>> list = new ImportExcelUtil().getListByExcel1(in,file.getOriginalFilename());
        in.close();
        ResultUtils result =  userService.batchInsertUser(list);
        ResultUtils.responseResult(httpServletResponse,result);
    }

    /**
     * 系统日志页面
     */
    @GetMapping("/systemLog")
    public ModelAndView sysLogModelAndView(ModelAndView modelAndView) {
        modelAndView.setViewName("systemControl/systemLog");
        return modelAndView;
    }

    /**
     * 系统日志查询
     */
    @ResponseBody
    @PostMapping("/systemLog")
    @PreAuthorize("hasAuthority('admin') or hasAuthority('管理员')" )
    public void sysLog(HttpServletResponse httpServletResponse, @ModelAttribute("queryParam") QueryParam queryParam) throws IOException {
        PageUtils.startPage(new PageParam(queryParam.getiDisplayStart(),queryParam.getiDisplayLength(),queryParam.getsSortDir(),queryParam.getsSortCol()));

        List<OperationLog> operationLogList = operationLogMapper.getOperLogByKeyword(queryParam);
        TableDataInfo tableDataInfo = PageUtils.getDataTable(operationLogList);

        ResultUtils result =  ResultUtils.succ(200,"获取系统日志信息成功",tableDataInfo);
        ResultUtils.responseResult(httpServletResponse,result);
    }

    /**
     * 导出系统日志
     */
    @RequestMapping("/systemLog/exprotData")
    @PreAuthorize("hasAuthority('admin') or hasAuthority('管理员')" )
    public void exprotLog(HttpServletRequest request, @ModelAttribute("queryParam") QueryParam queryParam,
                          HttpServletResponse response) {
        String[] excelHeader = {"序号", "操作时间", "IP地址", "操作内容","操作对象"};
        String[] ds_titles = {"index", "time", "ip", "logdesc","username"};
        int[] widths = {256 * 14, 256 * 24, 256 * 24, 256 * 32,256 * 24};
        int[] ds_format = {2, 2, 2, 1,2};
        try {
            List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
            List<OperationLog> list = operationLogMapper.getOperLogByKeyword(queryParam);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (list != null && !list.isEmpty()) {
                int index = 1;
                for (OperationLog rdata : list) {
                    Map<String, Object> map2 = new HashMap<String, Object>();
                    map2.put("index", index);
                    index++;
                    map2.put("time", rdata.getTime() != null ? format.format(rdata.getTime()) : "");
                    map2.put("ip", rdata.getIp());
                    map2.put("logdesc", rdata.getLogdesc());
                    map2.put("username", rdata.getUsername());
                    data.add(map2);
                }
            }
            ExcelUtil.export("系统日志数据", "数据列表", excelHeader, ds_titles, ds_format, widths, data, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
